package Presenter;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import Models.PSOFullfillment;

public class PSOFullfillmentPresenter extends AbstractPresenter<PSOFullfillment> {
	final String SINGLEITEM = "psoFullfillment";
	final String MULTIITEM = "psoFullfillments";
	
	public ArrayList<PSOFullfillment> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public PSOFullfillment tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public PSOFullfillment createItemFromJSONObject(JSONObject jsonObject){
		PSOFullfillment item = new PSOFullfillment();
		try{
			item.setPsoKegList(jsonObject.getString("kegList"));
			
			if(!jsonObject.isNull("soNum")){
				SalesOrderPresenter presenter = new SalesOrderPresenter();
				JSONObject jsonGroup = jsonObject.getJSONObject("soNum");
				item.setPsoSONum(presenter.createItemFromJSONObject(jsonGroup));
			} else {
				item.setPsoSONum(null);
			}
			
			if(!jsonObject.isNull("pso")){
				PendingSOPresenter presenter = new PendingSOPresenter();
				JSONObject jsonGroup = jsonObject.getJSONObject("pso");
				item.setPso(presenter.createItemFromJSONObject(jsonGroup));
			} else {
				item.setPso(null);
			}
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(PSOFullfillment item){
		try{
			JSONObject json = new JSONObject();
			json.put("kegList", item.getPsoKegList());
			
			if(item.getPsoSONum()!=null){
				SalesOrderPresenter presenter = new SalesOrderPresenter();
				json.put("soNum", presenter.createJSON(item.getPsoSONum()));
			} else {
				json.put("soNum", JSONObject.NULL);
			}
			
			if(item.getPso()!=null){
				PendingSOPresenter presenter = new PendingSOPresenter();
				json.put("pso", presenter.createJSON(item.getPso()));
			} else {
				json.put("pso", JSONObject.NULL);
			}
			
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public PSOFullfillment getEmptyEntity(){
		PSOFullfillment entity = new PSOFullfillment();
		return entity;
	}

}
